"""
Based on Rombach, Robin, et al. "High-resolution image synthesis with latent diffusion models." Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition. 2022.
"""
from inspect import isfunction
import math
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from .nn import (
    checkpoint,
)



def exists(val):
    return val is not None


def uniq(arr):
    return{el: True for el in arr}.keys()


def default(val, d):
    if exists(val):
        return val
    return d() if isfunction(d) else d


def max_neg_value(t):
    return -torch.finfo(t.dtype).max


def init_(tensor):
    dim = tensor.shape[-1]
    std = 1 / math.sqrt(dim)
    tensor.uniform_(-std, std)
    return tensor


# feedforward
class GEGLU(nn.Module):
    def __init__(self, dim_in, dim_out):
        super().__init__()
        self.proj = nn.Linear(dim_in, dim_out * 2)

    def forward(self, x):
        x, gate = self.proj(x).chunk(2, dim=-1)
        return x * F.gelu(gate)


class FeedForward(nn.Module):
    def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
        super().__init__()
        inner_dim = int(dim * mult)
        dim_out = default(dim_out, dim)
        project_in = nn.Sequential(
            nn.Linear(dim, inner_dim),
            nn.GELU()
        ) if not glu else GEGLU(dim, inner_dim)

        self.net = nn.Sequential(
            project_in,
            nn.Dropout(dropout),
            nn.Linear(inner_dim, dim_out)
        )

    def forward(self, x):
        return self.net(x)


def zero_module(module):
    """
    Zero out the parameters of a module and return it.
    """
    for p in module.parameters():
        p.detach().zero_()
    return module


def Normalize(in_channels):
    return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)


class LinearAttention(nn.Module):
    def __init__(self, dim, heads=4, dim_head=32):
        super().__init__()
        self.heads = heads
        hidden_dim = dim_head * heads
        self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias = False)
        self.to_out = nn.Conv2d(hidden_dim, dim, 1)

    def forward(self, x):
        b, c, h, w = x.shape
        qkv = self.to_qkv(x)
        q, k, v = rearrange(qkv, 'b (qkv heads c) h w -> qkv b heads c (h w)', heads = self.heads, qkv=3)
        k = k.softmax(dim=-1)  
        context = torch.einsum('bhdn,bhen->bhde', k, v)
        out = torch.einsum('bhde,bhdn->bhen', context, q)
        out = rearrange(out, 'b heads c (h w) -> b (heads c) h w', heads=self.heads, h=h, w=w)
        return self.to_out(out)


class SpatialSelfAttention(nn.Module):
    def __init__(self, in_channels):
        super().__init__()
        self.in_channels = in_channels

        self.norm = Normalize(in_channels)
        self.q = torch.nn.Conv2d(in_channels,
                                 in_channels,
                                 kernel_size=1,
                                 stride=1,
                                 padding=0)
        self.k = torch.nn.Conv2d(in_channels,
                                 in_channels,
                                 kernel_size=1,
                                 stride=1,
                                 padding=0)
        self.v = torch.nn.Conv2d(in_channels,
                                 in_channels,
                                 kernel_size=1,
                                 stride=1,
                                 padding=0)
        self.proj_out = torch.nn.Conv2d(in_channels,
                                        in_channels,
                                        kernel_size=1,
                                        stride=1,
                                        padding=0)

    def forward(self, x):
        h_ = x
        h_ = self.norm(h_)
        q = self.q(h_)
        k = self.k(h_)
        v = self.v(h_)

        # compute attention
        b,c,h,w = q.shape
        q = rearrange(q, 'b c h w -> b (h w) c')
        k = rearrange(k, 'b c h w -> b c (h w)')
        w_ = torch.einsum('bij,bjk->bik', q, k)

        w_ = w_ * (int(c)**(-0.5))
        w_ = torch.nn.functional.softmax(w_, dim=2)

        # attend to values
        v = rearrange(v, 'b c h w -> b c (h w)')
        w_ = rearrange(w_, 'b i j -> b j i')
        h_ = torch.einsum('bij,bjk->bik', v, w_)
        h_ = rearrange(h_, 'b c (h w) -> b c h w', h=h)
        h_ = self.proj_out(h_)

        return x+h_


class CrossAttention(nn.Module):
    """
    Cross-Attention 模块：Query 来自输入 x，Key/Value 来自 context。
    用于将外部条件（如 PSF）注入 U-Net 特征。
    """
    def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0):
        """
        参数:
            query_dim (int): 输入 query 的特征维度（通常是 U-Net 特征维度）
            context_dim (int): context 的特征维度（PSF 编码后的维度）
            heads (int): 注意力头数
            dim_head (int): 每个头的维度
            dropout (float): 输出 dropout 概率
        """
        super().__init__()
        inner_dim = heads * dim_head
        context_dim = default(context_dim, query_dim)  # 默认 context_dim = query_dim

        self.scale = dim_head ** -0.5
        self.heads = heads

        self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
        self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
        self.to_v = nn.Linear(context_dim, inner_dim, bias=False)

        self.to_out = nn.Sequential(
            nn.Linear(inner_dim, query_dim),
            nn.Dropout(dropout)
        )

    def forward(self, x, context=None, mask=None):
        """
        前向传播。

        参数:
            x (torch.Tensor): 输入特征，形状 (B, N, D), N = H*W
            context (torch.Tensor): 上下文特征（如 PSF 编码），形状 (B, L, C)
            mask (torch.Tensor): 注意力掩码，形状 (B, L)

        返回:
            torch.Tensor: 融合后的特征，形状 (B, N, D)
        """
        h = self.heads

        q = self.to_q(x)  # (B, N, h*d)

        context = default(context, x)
        k = self.to_k(context)  # (B, L, h*d)
        v = self.to_v(context)  # (B, L, h*d)

        # 重塑为多头形式
        q = rearrange(q, 'b n (h d) -> (b h) n d', h=h)  # (B*h, N, d)
        k = rearrange(k, 'b n (h d) -> (b h) n d', h=h)  # (B*h, L, d)
        v = rearrange(v, 'b n (h d) -> (b h) n d', h=h)  # (B*h, L, d)

        # 计算注意力分数
        sim = torch.einsum('b i d, b j d -> b i j', q, k) * self.scale  # (B*h, N, L)

        # 应用掩码（如果提供）
        if exists(mask):
            mask = rearrange(mask, 'b j -> b () j')
            mask = repeat(mask, 'b () j -> (b h) () j', h=h)
            max_neg = -torch.finfo(sim.dtype).max
            sim.masked_fill_(~mask, max_neg)

        # Softmax 得到注意力权重
        attn = sim.softmax(dim=-1)  # (B*h, N, L)

        # 加权求和
        out = torch.einsum('b i j, b j d -> b i d', attn, v)  # (B*h, N, d)
        out = rearrange(out, '(b h) n d -> b n (h d)', h=h)  # (B, N, h*d)

        # 输出映射
        return self.to_out(out)


class BasicTransformerBlock(nn.Module):
    """
    基本 Transformer 块，包含：
    - 自注意力 (Self-Attention)
    - 交叉注意力 (Cross-Attention with context)
    - 前馈网络 (Feed-Forward)
    每层后接 LayerNorm 和残差连接。
    """
    def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True):
        """
        参数:
            dim (int): 特征维度
            n_heads (int): 注意力头数
            d_head (int): 每个头的维度
            dropout (float): Dropout 概率
            context_dim (int): context 的维度
            gated_ff (bool): 是否使用门控前馈网络
            checkpoint (bool): 是否使用梯度检查点节省显存
        """
        super().__init__()
        self.attn1 = CrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout)
        self.ff = FeedForward(dim, mult=4, dropout=dropout, glu=gated_ff)
        self.attn2 = CrossAttention(query_dim=dim, context_dim=context_dim,
                                    heads=n_heads, dim_head=d_head, dropout=dropout)

        self.norm1 = nn.LayerNorm(dim)
        self.norm2 = nn.LayerNorm(dim)
        self.norm3 = nn.LayerNorm(dim)
        self.checkpoint = checkpoint

    def forward(self, x, context=None):
        if self.checkpoint:
            return checkpoint(self._forward, (x, context), self.parameters(), True)
        else:
            return self._forward(x, context)

    def _forward(self, x, context=None):
        # Self-Attention
        x = self.attn1(self.norm1(x)) + x
        # Cross-Attention (with PSF or other condition)
        x = self.attn2(self.norm2(x), context=context) + x
        # Feed-Forward
        x = self.ff(self.norm3(x)) + x
        return x


class SpatialTransformer(nn.Module):
    """
    空间 Transformer 模块，用于将交叉注意力机制引入 U-Net 的中间层。
    将图像特征展平为序列，应用 Transformer，再恢复为图像格式。
    """
    def __init__(self, in_channels, n_heads, d_head=64, depth=1, dropout=0., context_dim=1024):
        """
        参数:
            in_channels (int): 输入张量的通道数。
            n_heads (int): 注意力头的数量。
            d_head (int, 可选): 每个注意力头的维度，默认为 512。
            depth (int, 可选): 堆叠的 BasicTransformerBlock 模块的数量，默认为 1。
            dropout (float, 可选): Dropout 概率，默认为 0。
            context_dim (int, 可选): 上下文信息的维度，默认为 512。
        """
        super().__init__()
        self.in_channels = in_channels
        inner_dim = n_heads * d_head
        self.norm = nn.GroupNorm(32, in_channels) if in_channels % 32 == 0 else nn.GroupNorm(1, in_channels)

        # 投影到隐空间
        self.proj_in = nn.Conv2d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
        # 投影回原空间
        self.proj_out = zero_module(nn.Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0))

        # 堆叠 BasicTransformerBlock
        self.transformer_blocks = nn.ModuleList([
            BasicTransformerBlock(
                dim=inner_dim,
                n_heads=n_heads,
                d_head=d_head,
                dropout=dropout,
                context_dim=context_dim
            )
            for _ in range(depth)
        ])

    def forward(self, x, context):
        """
        前向传播。

        参数:
            x (torch.Tensor): 输入特征图，形状 (B, C, H, W)
            context (torch.Tensor): 上下文特征，形状 (B, L, context_dim)

        返回:
            torch.Tensor: 输出特征图，形状 (B, C, H, W)
        """
        dtype = self.proj_in.weight.dtype
        x = x.to(dtype=dtype)
        context = context.to(dtype=dtype)
        b, c, h, w = x.shape
        x_in = x

        # 归一化和投影
        x = self.norm(x)
        x = self.proj_in(x)  # (B, inner_dim, H, W)

        # 展平为空间序列
        x = rearrange(x, 'b c h w -> b (h w) c')

        # 通过多个 Transformer 块
        for block in self.transformer_blocks:
            x = block(x, context=context)

        # 恢复空间结构
        x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w)
        x = self.proj_out(x)

        # 残差连接
        return x + x_in